<template>
    <basic-container>

      <template>
        <div class="form-designer">
          <el-container>
            <el-main>
                <div style="height: 50px;border-left: 1px solid #e0e0e0;line-height: 50px;padding-left:5px ">
               产线类型:<el-select v-model="productLineType" placeholder="请选择产线类型"  disabled filterable clearable style="width:200px;margin-right: 5px">
                  <el-option
                    v-for="item in productLineTypeList"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                  实际产线名称：<avue-input v-model="realityLineName"  style="width:140px;margin-right: 5px" placeholder="请输入实际产线名称" ></avue-input>
                  品号：<avue-input v-model="articleNumber" disabled style="width:140px;margin-right: 5px" placeholder="请输入品号" ></avue-input>
                  工艺产线:<el-select v-model="craftLineId" placeholder="请选择工艺产线"  filterable  style="width:200px;margin-right: 5px">
                            <el-option
                              @click.native="craftLineChange(item)"
                              v-for="item in craftProductList"
                              :key="item.id"
                              :label="item.productProcessName"
                              :value="item.id">
                              <span style="float: left">{{ item.productProcessName }}</span>
                              <span style="float: right; color: #5e80a6; font-size: 13px">品号：{{ item.articleNumber }}</span>
                            </el-option>
                          </el-select>
                  组织:<el-select v-model="organizationId" placeholder="请选择组织"  filterable  style="width:200px;margin-right: 5px">
                  <el-option
                    @click.native="organizationChange(item)"
                    v-for="item in organizationList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                  <el-button type="primary" @click="saveLine">保存</el-button>
                </div>
                <avue-flow :height="800"
                                  width="100%"
                                  ref="flow"
                                  :option="option"
                                  v-model="flowForm">
                <template #header="{node}" >
                  {{(node || {}).name}}
                </template>
                <template slot-scope="{node}">
                  <el-descriptions  class="margin-top"  title="工序属性" :column="1" size="small" border >
                    <el-descriptions-item v-for="attr in processAttributeList" :label="attr.attributeName">
                      <avue-select   v-model="form[node.id+`_`+attr.attributeField]" disabled multiple v-if="attr.attributeName!='设备' && attr.attributeName!='工具'&& attr.attributeName!='夹具'" filterable clearable  dialogWidth="100%"  :placeholder="`请选择`+attr.attributeName"  :props="{label: 'label',value: 'value'}"  :dic=" processAttributeDataList[attr.attributeField]" ></avue-select>

                      <deviceSelect   :ref="node.id+`_`+attr.attributeField+`Page`"
                                      v-model="form[node.id+`_`+attr.attributeField]"
                                      v-if="(attr.attributeName=='设备' || attr.attributeName=='工具'|| attr.attributeName=='夹具') && processAttributeDataList[attr.attributeField]!=null"
                                      :attributeName="attr.attributeName"
                                      :attributeField="attr.attributeField"
                                      :organizationName="organizationName"
                                      :deviceClass="form[node.id+`_deviceClass`]"
                                      :nodeId = "node.id"
                                      :seleteOptions="processAttributeDataList[attr.attributeField]"
                                      @handleSelectData = "handleSelectData"/>
                      <div element-loading-text="拼命加载中"  element-loading-spinner="el-icon-loading" v-loading="(attr.attributeName=='设备' || attr.attributeName=='工具'|| attr.attributeName=='夹具') && processAttributeDataList[attr.attributeField]==null"></div>

                    </el-descriptions-item>
                    <el-descriptions-item label="设备分类">
                      <avue-select   v-model="form[node.id+`_deviceClass`]" filterable clearable  disabled dialogWidth="100%"  multiple placeholder="请选择设备分类"  :props="{label: 'label',value: 'value'}"  :dic="deviceClassList" ></avue-select>
                    </el-descriptions-item>
                  </el-descriptions>
                </template>
              </avue-flow>
            </el-main>
          </el-container>
        </div>
      </template>


      <template>
      </template>
    </basic-container>
</template>

<script>
    import { getProcessAttributeList,getProcessAttributeDataAllList,getDeviceClassList,getOrganizationList} from '@/api/pfoc/processattribute'
    import {getCraftLineAndDetailsList} from '@/api/pfoc/craftproductline'
    import {saveRealityLine} from '@/api/pfoc/realityproductline'
    /**引入设备下拉框*/
    import deviceSelect from '@/views/pfoc/realityproductline/custom-select'
    export default {
        name: "add-reality-line",
        props:{
            productLineTypeList:{//产线类型集合
                type:Array
            }
        },
        components: {
            //设备下拉框
            deviceSelect,
        },
         data() {
            return {
                count: 0,
                nodeCount:0,//节点下标
                form: [],//提交时数据集合
                flowForm:'',
                craftProductList:[],//工艺产线集合
                processAttributeList:[],//工序通用属性集合
                processAttributeDataList:[],//工序通用属性数据集合
                deviceClassList:[],//设备分类集合
                articleNumber:null,//品号
                craftLineName:null,//工艺产线名称
                craftLineId:null,//工艺产线ID
                organizationList:null,//组织集合
                organizationId:null,//组织ID
                organizationName:null,//组织名称
                craftLineMainData:{},//工艺产线主变数据
                craftLineSubData:[],//工艺产线子表数据
                option: {
                    name: null,
                    nodeList: [],//工序节点集合
                    lineList: [],//工序各节点指向顺序集合
                },
                realityLineName:null,//实际产线名称
                productLineType:null,//产线类型


            };
        },
        created() {
        },
        computed: {
            nodeList () {
                return this.option.nodeList
            },
        },
        mounted() {
            this.nodeCount = this.option.nodeList.length;//初始化节点下标
            //获取所有配置好的工艺产线及其对应工艺工序详情数据集合
            this.getCraftLineAndDetailsListData();
            //获取组织
            this.getOrganizationListData();
            //获取通用工序属性
            this.getProcessAttributeListData();
            //获取通用工序属性数据
            this.getProcessAttributeDataListData();
            //获取设备分类数据
            this.getDeviceClassListData();

        },
        methods: {
            //工艺产线选择
            craftLineChange(row){
                this.$refs.flow.resetPlumb();//清空画布
                for(var i= this.option.nodeList.length-1;i>=0;i--){
                    var id  =this.option.nodeList[i].id;
                    for (var j = 0; j < this.processAttributeList.length; j++) {
                        this.$delete(this.form, id + "_" + this.processAttributeList[j].attributeField)
                        this.$delete(this.form, id + "_" + this.processAttributeList[j].attributeField + "Name");//注册动态节点-设备名称
                    }
                    this.$delete(this.form, id+"_deviceClass");
                    //作业指导书
                    this.$delete(this.form, id+ "_workingBook");//注册动态节点-作业指导书
                    //作业指导书名称
                    this.$delete(this.form, id+ "_workingBookName");//注册动态节点-作业指导书名称
                }
                //获取工艺产线主表数据
                this.craftLineMainData= row;//工艺产线主变数据
                //获取工艺产线子表数据
                this.craftLineSubData = row.listCraftLineDetails;//工艺产线子表数据
                this.articleNumber=this.craftLineMainData.articleNumber;//品号
                this.craftLineName=this.craftLineMainData.craftLineName;//工艺产线名称
                this.productLineType=this.craftLineMainData.productLineType;//产线类型
                //设置反显工序
                this.option.nodeList = JSON.parse(this.craftLineMainData.processNodes);
                //设置反显工序指向顺序
                this.option.lineList =  JSON.parse(this.craftLineMainData.processNodeLine);
                //初始化节点下标
                var n =  this.option.nodeList[ this.option.nodeList.length-1].id;
                this.nodeCount = parseInt(n.split("node")[1])+1;

                //注册动态节点变量
                for(var n=0;n<this.craftLineSubData.length;n++) {
                    var  nodeId = this.craftLineSubData[n].nodeId;
                    for (var i = 0; i < this.processAttributeList.length; i++) {
                        var valueStr = this.craftLineSubData[n][this.processAttributeList[i].attributeField];
                        if(this.validatenull(valueStr)){//判空
                            this.$set(this.form, nodeId+"_"+this.processAttributeList[i].attributeField,valueStr);
                        }else{
                            this.$set(this.form, nodeId+"_"+this.processAttributeList[i].attributeField,valueStr.split(","));
                        }
                    }
                    if(this.validatenull(this.craftLineSubData[n].deviceClass)){
                        this.$set(this.form, nodeId+ "_deviceClass", this.craftLineSubData[n].deviceClass);//注册动态节点-设备类型
                    }else {
                        this.$set(this.form, nodeId + "_deviceClass", this.craftLineSubData[n].deviceClass.split(","));//注册动态节点-设备类型
                    }
                    //作业指导书
                    this.$set(this.form, nodeId+ "_workingBook", this.craftLineSubData[n].workingBook);//注册动态节点-作业指导书
                    //作业指导书名称
                    this.$set(this.form, nodeId+ "_workingBookName", this.craftLineSubData[n].workingBookName);//注册动态节点-作业指导书名称
                }

                //重新初始化flow组件
                this.$refs.flow.init();
                //重置自定义下拉框选项
                if(!this.validatenull(this.processAttributeDataList)) {
                    for (var i = 0; i < this.option.nodeList.length; i++) {
                        var nodeId = this.option.nodeList[i].id;
                        var obj = new Object();//创建对象
                        //循环工序属性取出每个工序的个属性数据加入到对象
                        for (var j = 0; j < this.processAttributeList.length; j++) {
                            if (this.processAttributeList[j].attributeName == '设备' || this.processAttributeList[j].attributeName == '工具' || this.processAttributeList[j].attributeName == '夹具') {
                                let ref = nodeId + "_" + this.processAttributeList[j].attributeField + "Page";//获取到当前的ref
                                this.$nextTick(() => {
                                    this.$refs[ref][0].deviceSelectInit();
                                })
                            }

                        }
                    }
                }
                 console.log(this.form)
                // console.log(this.option.nodeList)
                // console.log(row)

            },
            //组织选择
            organizationChange(row){
                this.organizationName = row.label;
                if(!this.validatenull(this.processAttributeDataList)) {
                    for (var i = 0; i < this.option.nodeList.length; i++) {
                        var nodeId = this.option.nodeList[i].id;
                        var obj = new Object();//创建对象
                        //循环工序属性取出每个工序的个属性数据加入到对象
                        for (var j = 0; j < this.processAttributeList.length; j++) {
                            if (this.processAttributeList[j].attributeName == '设备' || this.processAttributeList[j].attributeName == '工具' || this.processAttributeList[j].attributeName == '夹具') {
                                let ref = nodeId + "_" + this.processAttributeList[j].attributeField + "Page";//获取到当前的ref
                                this.$nextTick(() => {
                                    this.$refs[ref][0].deviceSelectInit();
                                })
                            }

                        }
                    }
                }

            },
            //获取所有配置好的工艺产线及其对应工艺工序详情数据集合
            getCraftLineAndDetailsListData(){
                getCraftLineAndDetailsList().then(response => {
                    this.craftProductList=response.data.data;
                    // console.log(this.pfocProcessList)
                })

            },

            //获取所有组织数据
            getOrganizationListData(){
                getOrganizationList().then(response => {
                    this.organizationList=response.data.data;
                })

            },
            //获取通用工序属性
            getProcessAttributeListData(){
                getProcessAttributeList().then(response => {
                    this.processAttributeList=response.data.data;
                    // console.log(this.processAttributeList)
                })

            },
            //获取通用工序属性数据
            getProcessAttributeDataListData(){
                getProcessAttributeDataAllList().then(response => {
                    this.processAttributeDataList=response.data.data;
                    for(var i=0;i<this.option.nodeList.length;i++){
                        var nodeId = this.option.nodeList[i].id;
                        var obj = new Object();//创建对象
                        //循环工序属性取出每个工序的个属性数据加入到对象
                        for(var j=0;j<this.processAttributeList.length;j++){
                            if(this.processAttributeList[j].attributeName=='设备' || this.processAttributeList[j].attributeName=='工具'|| this.processAttributeList[j].attributeName=='夹具'){
                                let ref = nodeId+"_"+this.processAttributeList[j].attributeField+"Page";//获取到当前的ref
                                this.$nextTick(() => {
                                    this.$refs[ref][0].deviceSelectInit();
                                })
                            }

                        }
                    }


                })
            },
            //获取设备分类数据
            getDeviceClassListData(){
                getDeviceClassList().then(response => {
                    this.deviceClassList=response.data.data;
                    // console.log(this.deviceClassList)
                })
            },
            //保存工艺产线
            saveLine(){
                if(this.validatenull(this.realityLineName)){
                    this.$message.warning("请输入实际产线名称。")
                    return;
                }
                if(this.validatenull(this.craftLineName)){
                    this.$message.warning("请选择工艺产线。")
                    return;
                }
                if(this.validatenull(this.articleNumber)){
                    this.$message.warning("品号不能为空。")
                    return;
                }
                if(this.validatenull(this.option.nodeList)){
                    this.$message.warning("请选择工艺产线。")
                    return;
                }
                if(this.validatenull(this.organizationName)){
                    this.$message.warning("请选择组织。")
                    return;
                }
              //组装需要提交的数据-实际产线主表数据组装
                var params = {};//主表参数集合
                params.realityLineName = this.realityLineName;//实际产线名称
                params.articleNumber = this.articleNumber;//品号
                params.craftLineName = this.craftLineName;//工艺产线名称
                params.organizationName = this.organizationName;//组织名称
                params.organizationId = this.organizationId;//组织ID
                params.productLineType = this.productLineType;//产线类型名称
                params.processNodes = JSON.stringify(this.option.nodeList);//工序节点集合（其中mark字段为工序ID）
                params.processNodeLine = JSON.stringify(this.option.lineList);//工序各节点指向顺序集合

               //组装需要提交的数据-实际产线子表数据组装
                var objArr = [];
                var messageArr=[];
                //循环工序节点集合
                for(var i=0;i<this.option.nodeList.length;i++){
                    var message = new Object();//未选择数据时错误消息对象
                    var error =[];//未选择数据时错误消息集合
                    var obj = new Object();//创建对象
                    //循环工序属性取出每个工序的个属性数据加入到对象
                    for(var j=0;j<this.processAttributeList.length;j++){
                        //将工序属性集合中的属性加入对象同时取出form集合中对应的属性数据放入属性对象中
                        if(!this.validatenull(this.form[this.option.nodeList[i].id+'_'+this.processAttributeList[j].attributeField])) {
                            obj[this.processAttributeList[j].attributeField] = this.form[this.option.nodeList[i].id + '_' + this.processAttributeList[j].attributeField].toString();
                        }else{
                            obj[this.processAttributeList[j].attributeField] =null;
                            error.push(this.processAttributeList[j].attributeName);
                        }
                        if(this.processAttributeList[j].attributeName=='设备' || this.processAttributeList[j].attributeName=='工具'|| this.processAttributeList[j].attributeName=='夹具'){
                            if(!this.validatenull(this.form[this.option.nodeList[i].id + '_' + this.processAttributeList[j].attributeField+ "Name"])){
                                obj[this.processAttributeList[j].attributeField + "Names"] = this.form[this.option.nodeList[i].id + '_' + this.processAttributeList[j].attributeField+ "Name"];
                            }else{
                                obj[this.processAttributeList[j].attributeField + "Names"] = null;
                            }
                        }

                    }
                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_deviceClass'])) {//设备分类
                        obj['deviceClass'] = this.form[this.option.nodeList[i].id + '_deviceClass'].toString();
                    }else{
                        obj['deviceClass'] = null
                        error.push("设备分类")
                    }
                    //作业指导书
                    obj['workingBook'] = this.form[this.option.nodeList[i].id + '_workingBook'];
                    //作业指导书名称
                    obj['workingBookName'] = this.form[this.option.nodeList[i].id + '_workingBookName'];
                    if(error.length>0){
                        message["工序"] = this.option.nodeList[i].name;
                        message["属性"] = error;
                        messageArr.push(message);
                    }
                    obj['processId'] = this.option.nodeList[i].mark;//取出工序ID加入对象
                    obj['processName'] = this.option.nodeList[i].name;//取出工序名称加入对象
                    obj['nodeId'] = this.option.nodeList[i].id;
                    obj['organizationName'] = this.organizationName;//组织名称
                    obj['organizationId'] = this.organizationId;//组织ID
                    //最后加入提交数据数组
                    objArr.push(obj)
                }
         /*       //漏填提醒
                if(!this.validatenull(messageArr)){
                    this.$message.warning(JSON.stringify(messageArr)+"——等数据未选择。")
                    return;
                }*/

                //组装需要提交的数据-实际产线设备配置表数据组装
                var deviceArr = [];
                //循环工序节点集合
                for(var i=0;i<this.option.nodeList.length;i++){
                    //循环工序属性取出每个工序的个属性数据加入到对象
                    for(var j=0;j<this.processAttributeList.length;j++){
                        //将工序属性集合中的属性加入对象同时取出form集合中对应的属性数据放入属性对象中
                        if(this.processAttributeList[j].attributeName=='设备'){
                            var deviceSnArr = this.form[this.option.nodeList[i].id + '_' + this.processAttributeList[j].attributeField];
                            var deviceNameArr = null;
                            if(!this.validatenull(this.form[this.option.nodeList[i].id + '_' + this.processAttributeList[j].attributeField+ "Name"])) {
                                deviceNameArr = this.form[this.option.nodeList[i].id + '_' + this.processAttributeList[j].attributeField + "Name"].split(',');
                            }
                            if(!this.validatenull(deviceSnArr)) {
                                for (var n = 0; n < deviceSnArr.length; n++) {
                                    var obj = new Object();//创建对象
                                    obj['deviceSn'] = deviceSnArr[n];//设备编码
                                    obj['deviceName'] = deviceNameArr[n];//设备名称
                                    obj['processId'] = this.option.nodeList[i].mark;//取出工序ID加入对象
                                    obj['processName'] = this.option.nodeList[i].name;//取出工序名称加入对象
                                    obj['nodeId'] = this.option.nodeList[i].id;
                                    obj['organizationName'] = this.organizationName;//组织名称
                                    obj['organizationId'] = this.organizationId;//组织ID
                                    //最后加入提交数据数组
                                    deviceArr.push(obj)
                                }
                            }
                        }
                    }

                }
                  console.log(objArr)
                var data={
                    realityProductLine:params,
                    realityProductLineDetailsList:objArr,
                    realityLineDeviceConfigList:deviceArr
                }
                //提交
                saveRealityLine(data).then(response => {
                    this.$message.success("保存成功。")
                    this.$emit('closeAddReality');//关闭新增页面
                });
            },
            handleClick (node) {
                this.$message.success(JSON.stringify(node))
            },
            handleNext () {
                this.count++
                if (this.count >= this.nodeList.length) {
                    this.count = 0;
                }
                this.flowForm = this.nodeList[this.count].id;
            },
            viewShunxu(){
                this.$message.success(JSON.stringify(this.option.lineList))
                /*this.$message.success(JSON.stringify(this.option.nodeList))*/
            },

            handleSelectData(obj){
                this.form[obj.nodeId+"_"+obj.attributeField] = obj.deviceSn;
                this.$set(this.form,obj.nodeId+"_"+obj.attributeField + "Name", obj.deviceName);//注册动态节点-设备名称
                // console.log(this.form)
            },
        }
    };
</script>

<style scoped>
  /deep/.avue-flow__node{
    height: auto!important;
  }
  /deep/ .avue-flow__node-header {
    line-height: 30px;
  }
  /deep/.el-descriptions__title {
    font-size: 14px;
    font-weight: 400;
    margin-top: 5px;
  }
</style>
